define(['request', 'template', 'jquery', 'cookie'], (request, template) => {
  class Header {
    constructor() {
      this.load().then(() => {
        //执行加载成功之后的逻辑
        this.search()
        this.seachvalue()
        this.getTabs()
        this.calcCartNum()
        this.displayUser()
        this.logOut()
      })
    }
    //加载头部html
    load () {
      return new Promise(resolve => {
        //加载成功之后resolve
        $('header').load('/html/modules/header.html', resolve)

      })
    }
    //完成搜索功能
    search () {
      $('#search').on('click', () => {
        $('.search-bar').toggle('slow', () => {
          $('.search-input').on('keyup', function () {
            $('.show').show()
            var wd = $(".search-input").val()
            var url = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' + wd;
            $.ajax({
              url: url,
              dataType: 'jsonp',
              data: '',
              jsonp: 'cb', /*百度接口的回调函数就是 cb*/
              success: function (data) {
                console.log(data);
                var str = '';
                for (var i = 0; i < data.s.length; i++) {
                  str += '<li>' + data.s[i] + '</li>';

                }
                $('.show').append(str);

              },
              timeout: 3000
            });
          })


        });

      })

    }
    seachvalue(){
      $('.show').on('click','li',function(){
       var value= $(this).text()
       $('.search-input').val(value)
      })
    }

    getTabs () {
      //调用request模块的方法，完成数据请求
      request.getTabs().then(resp => {
        if (resp.code === 200) {
          let { list } = resp.data
          list = list.slice(1, 7)
          const id = window.location.hash.slice(1)
          $('#tabList').html(template('tabsTemplate', { list, id }))
        }
      })
    }
    calcCartNum () {
      let cartList = localStorage.getItem('cart')
      if (cartList) {
        cartList = JSON.parse(cartList)
        let num = cartList.reduce((total, cart) => {
          total += cart.num
          return total
        }, 0)
        $('#shopnum').html(num)
      } else {
        $('#shopnum').html(0)
      }
    }

    //显示欢迎你xxx
    displayUser () {
      let info = $.cookie('userInfo')
      if (info) {
        let cookie = JSON.parse($.cookie('userInfo'))
        $('.login-success').show()
        $(' #login-name').html(cookie._username)
        $('#me').hide()
      } 
      else {
        $('#me').show()
        $('.login-success').hide()
      }
    }

    //注销
    logOut(){
      $('#logOff').on('click',function(){
        if(confirm('确认注销吗？')){
          $.removeCookie('userInfo',{ path: '/' })
          $('#me').show()
          $('.login-success').hide()
        }
      })

    }
  }
  return new Header()
}

);